package io.gitee.icefairy.total_monitor.task

import cn.hutool.cron.CronUtil
import cn.hutool.db.Db
import cn.hutool.db.Entity
import cn.hutool.log.LogFactory
import kotlinx.coroutines.channels.Channel
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.DependsOn
import org.springframework.stereotype.Component
import javax.annotation.PostConstruct

/**
 * AUTHOR:icefairy
 * DATE:2021/12/22 0022 19:18
 **/
@Component
@DependsOn("DbConfig")
open class ActiveLogTask {
    companion object {
        val chnLogs = Channel<Entity>(10000)
    }

    val log = LogFactory.get()

    @Autowired
    lateinit var db: Db

    @PostConstruct
    fun beginTask() {
        CronUtil.setMatchSecond(true)
        CronUtil.schedule("0 * * * * *", Runnable {
            try {
                val lst = mutableListOf<Entity>()
                while (lst.size < 10000) {
                    val res = chnLogs.tryReceive()
                    if (res.isSuccess) {
                        res.getOrNull()?.let {
                            lst.add(it)
                        }
                    } else if (res.isClosed) {
                        log.warn("队列已关闭")
                    } else if (res.isFailure) {
                        break
                    }
                }
                db.insert(lst)
                lst.clear()
            } catch (e: Exception) {
                log.error(e)
            }
        })
        CronUtil.start()
        log.info("Cron started")
    }
}